<?php
namespace Common\Logic;

/**
 * 客栈预定端支付相关设置，包含支付短信通知，结算方式，退订规则
 * @modify AmosZhong 2016-05-16 创建
 */
class HotelPayLogic extends \Common\Controller\BaseController {



    /**
     * 查询支付相关设置信息
     * @modify AmosZhong 2016-05-16 创建
     * @param  integer   $hotelId   客栈ID
     * @return mixin     查询结果
     */
    public function getPayDetail($hotelId) {
        $hotelPayDetailModel = D('HotelPayDetail');
        $hotelData = $hotelPayDetailModel->getInfoByHotel($hotelId);
        if (empty($hotelData)) {
            returnJson(500, 512, 'error');
        }

        return $hotelData;
    }

    /**
     * 获取商家自收信息
     * 方法不抛异常
     * @modify trainyao 2016-07-11 创建
     * @param  integer   $hotelId   客栈ID
     * @return array              信息数组 { type 
     *                                       partnerPayInfo { wechat{
     *                                                           'appid'
     *                                                           'appsecret'
     *                                                           'mchid'
     *                                                           'mchkey'
     *                                                           'mpverify'
     *                                                       }, ali{
     *                                                           'account'
     *                                                           'pid'
     *                                                           'key'
     *                                                       }}
     *                                     }
     */
    public function getPartnerPayInfo($hotelId) {
        $hotelPayDetailModel = D('HotelPayDetail');
        $hotelPayDetail = $hotelPayDetailModel->getInfoByHotel($hotelId);
        $returnData = array(
            'type' => $hotelPayDetail['type'],
            'partnerPayInfo' => array(
                'wechat' => array(
                    'appid' => '',
                    'appsecret' => '',
                    'mchid' => '',
                    'mchkey' => '',
                    'mpverify' => '',
                ),
                'ali' => array(
                    'account' => '',
                    'pid' => '',
                    'key' => '',
                ),
            ),
        );

        // 商家自收类型,前往获取信息
        $hotelPartnerPayModel = D('HotelPartnerPay');
        $hotelPartnerPayInfo = $hotelPartnerPayModel->getInfoByHotel($hotelId);
        if (!empty($hotelPartnerPayInfo)) {
            $returnData['partnerPayInfo'] = array(
                'wechat' => array(
                    'appid' => $hotelPartnerPayInfo['wechatappid'],
                    'appsecret' => $hotelPartnerPayInfo['wechatappsecret'],
                    'mchid' => $hotelPartnerPayInfo['wechatmchid'],
                    'mchkey' =>  $hotelPartnerPayInfo['wechatmchkey'],
                    'mpverify' => $hotelPartnerPayInfo['wechatmpverify'],
                ),
                'ali' => array(
                    'account' => $hotelPartnerPayInfo['aliaccount'],
                    'pid' => $hotelPartnerPayInfo['alipid'],
                    'key' => $hotelPartnerPayInfo['alikey'],
                ),
            );
        }

        return $returnData;
    }

    /**
     * 设置结算方式
     * @modify AmosZhong 2016-05-16 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string $hotelId       客栈Id
     * @param  string $accountMobile 结算短信号码
     * @param  string $accountType   账户类型
     * @param  string $bankName      开户行名称
     * @param  string $accountName   开户人姓名
     * @param  string $account       银行卡号
     * @return Boolean              执行结果
     */
    public function savePayDetail($hotelId, $accountMobile, $accountType, $bankName, $accountName, $account, $areaCode = '86') {
        $hotelPayDetailModel = D('HotelPayDetail');

        $result = $hotelPayDetailModel->saveInfo($hotelId, null, null, $accountMobile, $accountType, $bankName, $accountName, $account, null, null, null, $areaCode);
        if ($result) {
            return true;
        } else {
            returnJson(500, 508);
            return false;
        }
    }

    /**
     * 设置支付短信通知号码，最多设置一个
     * @modify AmosZhong 2016-05-16 创建
     * @modify wenhui 2017-05-04 增加国际手机检验
     * @param  integer   $hotelId   客栈ID
     * @param  string $hotelId       客栈Id
     * @param  string $payMobile     支付短信通知号码
     * @return Boolean              执行结果
     */
    public function savePayMobile($hotelId, $payMobile, $areaCode = '86') {
        $hotelPayDetailModel = D('HotelPayDetail');
        $hotelData = $hotelPayDetailModel->getInfoByHotel($hotelId);
        if (empty($hotelData)) {
            returnJson(500, 512, 'error');
        }

        if (!empty($hotelData['orderpaymobile']) && !empty($payMobile)) {
            returnJson(403, 412, 'error');
        }

        $result = $hotelPayDetailModel->saveInfo($hotelId, null, $payMobile, null, null, null, null, null, null, null, $areaCode, null);
        if ($result) {
            return true;
        } else {
            returnJson(500, 508);
            return false;
        }
    }

    /**
     * 设置退订规则
     * @modify AmosZhong 2016-05-16 创建
     * @modify trainyao 2016-06-20 添加押金信息
     * @param  integer   $hotelId   客栈ID
     * @param  string $hotelId       客栈Id
     * @param  string $refundRule    退订规则
     * @return Boolean              执行结果
     */
    public function savePayRefundRule($hotelId, $refundRule = null, $deposit = null) {
        $hotelPayDetailModel = D('HotelPayDetail');

        $result = $hotelPayDetailModel->saveInfo($hotelId, $refundRule, null, null, null, null, null, null, $deposit);
;
        if ($result) {
            return true;
        } else {
            returnJson(500, 508);
            return false;
        }
    }

    /**
     * 保存客栈支付类型
     * 方法会抛异常
     * @modify trainyao 2016-07-11 创建
     * @param  integer   $hotelId   客栈ID
     * @param  integer   $type      客栈微预定支付类型
     * @return boolean              保存结果
     */
    public function savePayType($hotelId, $type) {        

        $hotelPayUsableModel = D('HotelPayUsable');
        $hotelPayUsableInfo = $hotelPayUsableModel->getInfo($hotelId);
        $payUsable = array(
            'uclbrt_alipay_enable'=>!empty($hotelPayUsableInfo['uclbrtalipayenable']) && time()<strtotime($hotelPayUsableInfo['uclbrtalipayenddate']),
            'uclbrt_wechat_enable'=>!empty($hotelPayUsableInfo['uclbrtwechatenable']) && time()<strtotime($hotelPayUsableInfo['uclbrtwechatenddate']),
            'hotel_alipay_enable'=>!empty($hotelPayUsableInfo['hotelalipayenable']) && time()<strtotime($hotelPayUsableInfo['hotelalipayenddate']),
            'hotel_wechat_enable'=>!empty($hotelPayUsableInfo['hotelwechatenable']) && time()<strtotime($hotelPayUsableInfo['hotelwechatenddata']),
        );
       
        //开通检查
        if($type & 1){
            if(!$payUsable['uclbrt_alipay_enable']){
                throw new \Exception('403,608', 608);
                return false;
            }
        }
        if($type & 2){
            if(!$payUsable['uclbrt_wechat_enable']){
                throw new \Exception('403,608', 608);
                return false;
            }
        }        
        if($type & 48){
            // 如果类型是商家支付,需要检查微信或者支付宝支付信息是否完整
            $hotelPartnerPayModel = D('HotelPartnerPay');
            $hotelPartnerPayInfo = $hotelPartnerPayModel->getInfoByHotel($hotelId);
            if (empty($hotelPartnerPayInfo)) {
                throw new \Exception('403,604', 604);
                return false;
            }
            
            if($type & 16){
                if(!$payUsable['hotel_alipay_enable']){
                    throw new \Exception('403,608', 608);
                    return false;
                }
                $aliCanSave = !empty($hotelPartnerPayInfo['aliaccount']);
                $aliCanSave = $aliCanSave && !empty($hotelPartnerPayInfo['alipid']);
                $aliCanSave = $aliCanSave && !empty($hotelPartnerPayInfo['alikey']);
                if (!$aliCanSave) {
                    throw new \Exception('403,604', 604);
                    return false;
                }
            }
            if($type & 32){
                if(!$payUsable['hotel_wechat_enable']){
                    throw new \Exception('403,608', 608);
                    return false;
                }
                $wechatCanSave = !empty($hotelPartnerPayInfo['wechatappid']);
                $wechatCanSave = $wechatCanSave && !empty($hotelPartnerPayInfo['wechatappsecret']);
                $wechatCanSave = $wechatCanSave && !empty($hotelPartnerPayInfo['wechatmchid']);
                $wechatCanSave = $wechatCanSave && !empty($hotelPartnerPayInfo['wechatmchkey']);
                if (!$wechatCanSave) {
                    throw new \Exception('403,604', 604);
                    return false;
                }
            }
        }

        // 保存支付类型
        $hotelPayDetailModel = D('HotelPayDetail');
        $saveResult = $hotelPayDetailModel->saveInfo($hotelId, null, null, null, null, null, null, null, null, $type);
        if (empty($saveResult)) {
            throw new \Exception('500,506', 506);
            return false;
        }

        return true;
    }

    /**
     * 保存客栈最迟退房时间 最早入住时间
     * 方法会抛异常
     * @modify wenhui 2017-08-28 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $checkoutTime      客栈最迟退房时间
     * @param  string   $checkinTime      客栈最早入住时间
     * @return boolean              保存结果
     */
    /*public function saveCheckoutOrCheckinTime($hotelId, $checkoutTime, $checkinTime) {        
        // 保存数据
        $hotelInfoModel = D('HotelInfo');
        $saveResult = $hotelInfoModel->saveInfo($hotelId, $checkoutTime, $checkinTime);
        if ($saveResult == false) {
            throw new \Exception('500,506', 506);
            return false;
        }

        return true;
    }*/

    /**
     * 保存客栈支付信息
     * 方法会抛异常
     * @modify trainyao 2016-07-11 创建
     * @modify zhangzhen 2017-01-19 添加微信支付文件
     * @modify wenhui 2017-02-06 添加移动端版本判断
     * @param  integer   $hotelId   客栈ID
     * @param  mixin   $wechatPayInfo      微信支付信息数组 {appid, appsecret, mchid, mchkey},部分保存传null
     * @param  mixin   $aliPayInfo      支付宝支付信息数组 {account, pid, key},部分保存传null
     * @return boolean              保存结果
     */
    public function savePayInfo($hotelId, $wechatPayInfo = null, $aliPayInfo = null) {
        // 检查是否已经存在条目
        $hotelPartnerPayModel = D('HotelPartnerPay');
        $hotelPartnerPayInfo = $hotelPartnerPayModel->getInfoByHotel($hotelId);

        $wechatAppid = !is_null($wechatPayInfo) ? $wechatPayInfo['appid'] : null;
        $wechatAppsecret = !is_null($wechatPayInfo) ? $wechatPayInfo['appsecret'] : null;
        $wechatMchid = !is_null($wechatPayInfo) ? $wechatPayInfo['mchid'] : null;
        $wechatMchkey = !is_null($wechatPayInfo) ? $wechatPayInfo['mchkey'] : null;

        $wechatMpverify = !is_null($wechatPayInfo) ? $wechatPayInfo['mpverify'] : null;
        //创建js域名安全文件
        $wechatMpverify = strpos($wechatMpverify, '.') ? $wechatMpverify : $wechatMpverify . '.txt';
        if (!is_null($aliPayInfo)) {
            $wechatMpverify = null;
        } elseif ($wechatMpverify == $hotelPartnerPayInfo['wechatmpverify']) {
            $wechatMpverify = null;
        } else {
            if(!file_exists($wechatMpverify)) {
                unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $hotelPartnerPayInfo['wechatmpverify']);
                $mpverifyTxt = fopen($wechatMpverify, "w");
                $content = explode('_',$wechatMpverify);
                $content = explode('.',$content[2]);
                $result = fwrite($mpverifyTxt, $content[0]);
                if($result){
                    Vendor('phpRPC.phprpc_client');
                    $client = new \PHPRPC_Client(C('MANAGE_QRCLIENT_URL'));
                    $client->setEncryptMode(3);
                    $sendData = array(
                        'flag' => 'uclbrt',
                        'time' => time(),
                        'hotel' => $hotelId,
                        'wechatMpverify' => $wechatMpverify,
                        'oldFileName' => $hotelPartnerPayInfo['wechatmpverify'],
                    );
                    $result = $client->makeJsMpVerify($sendData);
                }
                if (empty($result)) {
                    throw new \Exception('500,513', 513);
                    return false;
                }
            }
        }

        $aliAccount = !is_null($aliPayInfo) ? $aliPayInfo['account'] : null;
        $aliPid = !is_null($aliPayInfo) ? $aliPayInfo['pid'] : null;
        $aliKey = !is_null($aliPayInfo) ? $aliPayInfo['key'] : null;
        if (empty($hotelPartnerPayInfo)) {
            // 条目不存在,新增
            $saveResult = $hotelPartnerPayModel->addInfo($hotelId, $wechatAppid, $wechatAppsecret, $wechatMchid, $wechatMchkey, $aliAccount, $aliPid, $aliKey,$wechatMpverify);
        } else {
            // 条目存在,修改
            $saveResult = $hotelPartnerPayModel->saveInfoByHotel($hotelId, $wechatAppid, $wechatAppsecret, $wechatMchid, $wechatMchkey, $aliAccount, $aliPid, $aliKey,$wechatMpverify);
        }
        if (empty($saveResult)) {
            throw new \Exception('500,506', 506);
            return false;
        }

        return true;
    }

    /**
     * 获取对账信息,并进行筛选分页
     * @modify trainyao 2016-05-18 创建
     * @param  integer   $hotelId   客栈ID
     * @param  integer   $status   对账状态
     * @param  string   $startDate   支付时间区间开始
     * @param  integer   $endDate   支付时间区间结束
     * @param  integer   $mobile   预定人手机号
     * @param  integer   $pageIndex   分页页码
     * @param  integer   $pageSize   分页每页数量
     * @param  integer   $type   代收类型 0=畅联代收 1=商家自收
     * @return array              array(
     *                                 info => array(array(), array())
     *                                 page => array(  //分页信息,若不传pageIndex,没有该数组
     *                                     current  当前页码
     *                                     size  每页数目
     *                                     total  总数
     *                                     pageTotal  页数总数
     *                                 )
     *                            )
     */
    public function getReconciliationItem($hotelId, $status = null, $startDate = null, $endDate = null, $mobile = null, $pageIndex = null, $pageSize = null, $isUclbrt = true) {
        
        $orderPayInfoModel = D('OrderPayInfo');
        $orderPayInfo = $orderPayInfoModel->getInfoByHotelType($hotelId, $isUclbrt?array(PAY_TYPE_UCLBRT_ALIPAY,PAY_TYPE_UCLBRT_WECHAT):array(PAY_TYPE_HOTEL_ALIPAY,PAY_TYPE_HOTEL_WECHAT));
        if (empty($orderPayInfo)) {
            return array('info' => array());
        }

        // status筛选(查询畅联代收才需要筛选)
        if ($isUclbrt && !is_null($status)) {
            foreach ($orderPayInfo as $index => $orderPayInfoItem) {
                if ($orderPayInfoItem['ischeck'] != $status) {
                    unset($orderPayInfo[$index]);
                }
            }
            unset($orderPayInfoItem);
        }
        if (empty($orderPayInfo)) {
            return array('info' => array());
        }

        // 日期筛选
        if (!is_null($startDate) && !is_null($endDate)) {
            foreach ($orderPayInfo as $index => $orderPayInfoItem) {
                if (!isBetweenTime($orderPayInfoItem['paytime'], $startDate, $endDate)) {
                    unset($orderPayInfo[$index]);
                }
            }
            unset($orderPayInfoItem);
        }
        if (empty($orderPayInfo)) {
            return array('info' => array());
        }

        // 预定手机号筛选
        $mobileFilte = !is_null($mobile);
        $orderRoomModel = D('OrderRoom');
        $orderRoomIds = array_unique(array_column($orderPayInfo, 'orderroom_id'));
        $orderRoomInfo = $orderRoomModel->getInfo($orderRoomIds);
        $orderInfoIds = array_unique(array_column($orderRoomInfo, 'orderinfo_id'));
        $orderRoomInfo = getArrayValueAsIndex($orderRoomInfo, 'id');
        $orderInfoModel = D('OrderInfo');
        $orderInfo = $orderInfoModel->getInfo($orderInfoIds);
        if (count($orderInfoIds) == 1) {
            $orderInfo = array($orderInfo);
        }
        $orderInfo = getArrayValueAsIndex($orderInfo, 'id');

        foreach ($orderPayInfo as $index => &$orderPayInfoItem) {
            $orderId = $orderRoomInfo[$orderPayInfoItem['orderroom_id']]['orderinfo_id'];
            if ($orderInfo['mobile'] != $mobile) {
                unset($orderPayInfo[$index]);
            } else {
                $orderPayInfoItem['order'] = $orderInfo[$orderId];
            }
        }
        unset($orderPayInfoItem);
        if (empty($orderPayInfo)) {
            return array('info' => array());
        }

        // 判断是否有权限查看信息
        $canSeeMobile = true;
        if (MODULE_NAME != 'Extend') {
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $canSeeMobile = $adminAuthorityLogic->check($hotelId, null, AUTHORITY_CONTACT_INFO_BLOCK);
        }
        if (!$canSeeMobile) {
            foreach ($orderPayInfo as &$orderPayInfoItem) {
                $orderPayInfoItem['order']['mobile'] = !empty($orderPayInfoItem['order']['mobile']) ? substr($orderPayInfoItem['order']['mobile'], 0, 3) . '********' : $orderPayInfoItem['order']['mobile'];
            }
            unset($orderPayInfoItem);
        }

        // 进行分页
        $orderPayInfo = $this->generatePageInfo(array_values($orderPayInfo), $pageIndex, $pageSize);

        // 返回信息
        return $orderPayInfo;
    }

    /**
     * 生成分页信息
     * @modify trainyao 2016-05-18  创建
     * @param  array   $orderPayInfo 退款信息数组
     * @param  integer   $pageIndex  页码
     * @param  integer   $pageSize   每页条目数目
     * @return array               信息数组
     */
    private function generatePageInfo($orderPayInfo, $pageIndex, $pageSize) {
        if (empty($pageIndex) || empty($pageSize)) {
            return array('info' => $orderPayInfo);
        }

        // 处理分页
        $orderPayInfo = createPageInfo($orderPayInfo, $pageIndex, $pageSize);
        $pageInfo = array(
            'current' => $orderPayInfo['current'],
            'size' => $orderPayInfo['size'],
            'total' => $orderPayInfo['total'],
            'pageTotal' => $orderPayInfo['pageTotal'],
        );
        $orderPayInfo = $orderPayInfo['data'];

        return array('info' => $orderPayInfo, 'page' => $pageInfo);
    }
}
